package process_demo.review.about_lock.locks;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author haomin
 * @date 2022/09/10 15:46
 **/
public class Main {
    static int r = 0;
    static class MyThread1 extends Thread{
        private Lock o;
        MyThread1(){}
        MyThread1(Lock o){
            this.o = o;
        }

        @Override
        public void run() {
            o.lock();
            try {
                for (int i = 0; i < 1000_0000; i++) {
                    r++;
                }
            }
            finally {
                o.unlock();
            }
        }
    }
    static class MyThread2 extends Thread{
        private Lock o;
        MyThread2(){}
        MyThread2(Lock o){
            this.o = o;
        }

        @Override
        public void run() {
            o.lock();
            try {
                for (int i = 0; i < 1000_0000; i++) {
                    r--;
                }
            }
            finally {
                o.unlock();
            }

        }
    }

    public static void main(String[] args) throws InterruptedException {
        Lock o = new ReentrantLock();
        MyThread1 t1 = new MyThread1(o);
        MyThread2 t2 = new MyThread2(o);
        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println(r);
    }
}